package resume

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"resume-server/internal/consts"
	"resume-server/internal/dao"
	"resume-server/internal/model"
	"resume-server/internal/model/entity"
	"resume-server/internal/service"
)

type sResume struct{}

func init() {
	service.RegisterResume(New())
}

func New() *sResume {
	return &sResume{}
}

func (s *sResume) Create(ctx context.Context, in model.AddResumeInput) (out *model.AddResumeOutput, err error) {

	id, err := dao.Resume.Ctx(ctx).Data(in).InsertAndGetId()
	if err != nil {
		return nil, err
	}

	return &model.AddResumeOutput{
		Id: uint64(id),
	}, err
}

func (s *sResume) Get(ctx context.Context, in model.GetResumeInput) (out *model.GetResumeOutput, err error) {

	out = new(model.GetResumeOutput)
	err = dao.Resume.Ctx(ctx).FieldsEx(dao.Resume.Columns().Id).Where(g.Map{dao.Resume.Columns().Id: in.Id}).Scan(&out)
	if err != nil {
		return nil, err
	}
	// scan默认不会将ID保存
	out.Id = in.Id
	return out, err
}

func (s *sResume) Update(ctx context.Context, in model.UpdateResumeInput) (out *model.UpdateResumeOutput, err error) {

	out = new(model.UpdateResumeOutput)
	_, err = dao.Resume.Ctx(ctx).Data(in).FieldsEx(dao.Resume.Columns().Id).Where(g.Map{
		dao.Resume.Columns().Id: in.Id,
	}).Update()

	if err != nil {
		return nil, err
	}

	return &model.UpdateResumeOutput{Id: in.Id}, err
}

func (s *sResume) GetList(ctx context.Context, in model.GetResumeListInput) (out *model.GetResumeListOutput, err error) {
	out = &model.GetResumeListOutput{Page: in.Page, Size: in.Size}

	if in.Size == 0 {
		out.Page = 0
		out.Size = consts.DefaultPageSize
	}

	m := dao.Resume.Ctx(ctx)
	entityList := make([]*entity.Resume, 0)
	err = m.Page(int(out.Page), int(out.Size)).Scan(&entityList)
	if err != nil {
		return nil, err
	}

	err = gconv.Scan(entityList, &out.ResumeList)
	if err != nil {
		return nil, err
	}
	out.Total = uint(len(entityList))

	return out, err
}
